/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sk.lieskove.jianghongtiao.common.utils.xml;

import org.apache.log4j.Logger;
import sk.lieskove.jianghongtiao.common.utils.PropertiesUtils;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.util.logging.Level;

/**
 * 
 * @author xjuraj e-mail: jjurco.sk_gmail.com
 */
public class Transformation implements Serializable {
    
    private static transient Logger log = Logger.getLogger(Transformation.class);
    private transient PropertiesUtils pu = new PropertiesUtils(Transformation.class);
    private static final transient TransformerFactory factory = TransformerFactory.newInstance();
    
    public static String applyTemplate(String xmlString, File template){
        log.debug("Enter applyTemplate(String, File)");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        applyTemplate(new ByteArrayInputStream(xmlString.getBytes()), os, template);
        String result = null;
        try {
            result = new String(os.toByteArray(), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            log.error("Unsupported encoding UTF-8.");
        }
        return result;
    }
    
    public static void applyTemplate(InputStream is, OutputStream os, File template){
        log.debug("Enter applyTemplate(InputStream, OutputStream, File)");
        try {
            Transformer transformer = null;
            synchronized(factory){
                transformer = factory.newTransformer(new StreamSource(template));
            }
            transformer.transform(new StreamSource(is), new StreamResult(os));
        } catch (TransformerConfigurationException ex) {
            java.util.logging.Logger.getLogger(Transformation.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            java.util.logging.Logger.getLogger(Transformation.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
